package com.wissen.ajaxservlet.client;

import javax.servlet.*;
import javax.servlet.http.*;

import java.sql.*;
import java.io.*;

@SuppressWarnings("serial")
/**
 * @author wissen16(mayur Birari)
 */
public class AjaxServlet extends HttpServlet {

	String username = "root";
	String password = "wissen";
	Connection con;
	ResultSet rs;
	PreparedStatement stmt;
	Statement stmt1;
	String url = "jdbc:mysql://localhost:3306/google";
	PrintWriter pw1;

	/**
	 * to get initialise connection classes 
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, username, password);
			// stmt = con.createStatement();
		} catch (Exception e) {
			System.out.println("Sql Error" + e.getMessage());
		}
	}
	
/**
 * to handle get request from requested page  
 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		pw1 = resp.getWriter();
		resp.setContentType("text/html");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, username, password);
			stmt1 = con.createStatement();
			rs = stmt1.executeQuery("select * from account");
			int ok = 0;
			String fname="";
			String lname="";
			String logname="";
			String pwd="";
			while (rs.next()) {
				 fname=String.valueOf(rs.getString(1));
				 lname=String.valueOf(rs.getString(2));
				 logname = String.valueOf(rs.getString(3));
				  pwd = String.valueOf(rs.getString(4));			
				 if(logname.equals(req.getParameter("slogn"))) {
					if (pwd.equals(req.getParameter("spwd"))) {
						ok = 1;
						break;
					} else {
						ok = -1;break;
					}
				}
			}
			if (ok == 1) {
				pw1.write("Login SuccessFully,"+fname+","+lname);
				//resp.sendRedirect("Editgmail.html?fname="+fname+"&lname="+lname+"&logn="+req.getParameter("lid")+"&pwd="+req.getParameter("pwd"));
			} else if (ok == -1) {
				pw1.write("Please Enter valid Password");
				 //resp.sendRedirect("Signupgmail.html");
			} else {
				pw1.write("Please Enter valid Login name");				
				//resp.sendRedirect("Signupgmail.html");
			}			
			rs.close();
			con.close();
		} catch (Exception e) {
			pw1.write(e.getMessage());
		}
	}

	/**
	 * to get destroy the memory occupy by objects  
	 */
	public void destroy() {
		super.destroy();
	}
}